package com.wenzhoujie.adapter;

import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout.LayoutParams;

import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lingou.www.R;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;
import com.wenzhoujie.AlbumActivity;
import com.wenzhoujie.BaseActivity;
import com.wenzhoujie.LoginNewActivity;
import com.wenzhoujie.MyPhotosAndLovesActivity;
import com.wenzhoujie.ShareDetailActivity;
import com.wenzhoujie.UserCenterActivity;
import com.wenzhoujie.app.App;
import com.wenzhoujie.app.AppHelper;
import com.wenzhoujie.fragment.ShareDetailFirstFragment;
import com.wenzhoujie.fragment.ShareDetailSecondFragment;
import com.wenzhoujie.http.InterfaceServer;
import com.wenzhoujie.library.adapter.SDBaseAdapter;
import com.wenzhoujie.library.customview.ScaleImageView;
import com.wenzhoujie.library.utils.SDToast;
import com.wenzhoujie.library.utils.SDViewBinder;
import com.wenzhoujie.library.utils.SDViewUtil;
import com.wenzhoujie.model.LocalUserModel;
import com.wenzhoujie.model.RequestModel;
import com.wenzhoujie.model.ShareItemCollectModel;
import com.wenzhoujie.model.ShareItemCommentListModel;
import com.wenzhoujie.model.ShareItemCommentModel;
import com.wenzhoujie.model.ShareItemImageModel;
import com.wenzhoujie.model.ShareItemModel;
import com.wenzhoujie.model.SharelistItemModel;
import com.wenzhoujie.model.SharelistItemModelnew;
import com.wenzhoujie.model.act.BaseActModel;
import com.wenzhoujie.model.act.ShareActModel;
import com.wenzhoujie.utils.JsonUtil;
import com.wenzhoujie.utils.SDInterfaceUtil;
import com.wenzhoujie.utils.SDMyImageGetterUtil;
import com.wenzhoujie.utils.SDTypeParseUtil;
import com.wenzhoujie.utils.ViewHolder;
import com.wenzhoujie.utils.ViewInject;

public class PhotosAdapter extends SDBaseAdapter<SharelistItemModelnew>
{
	private String uid;
	private BaseActivity nowActivity = null;
	private ImageView mIvShareuserimage = null;
	private TextView mTvUsername = null;
	private TextView mTvUsersource = null;
	private TextView mTvTime = null;
	private TextView mTvContent = null;
	
	public PhotosAdapter(List<SharelistItemModelnew> mListModelnew, Activity activity)
	{
		super(mListModelnew, activity);
		nowActivity = (BaseActivity) activity;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		if (convertView == null)
		{
			//convertView = mInflater.inflate(R.layout.item_my_photos, null);
			convertView = mInflater.inflate(R.layout.item_share2, null);
		}
		
		final View mView = convertView;
		final SharelistItemModelnew model = getItem(position);
		
		//System.out.println("parent: "+parent.getChildCount());
		//System.out.println("getRelay_count: "+model.getReply_count()+" getUser_avatar: "+model.getUseravatar()+" Shared: "+model.getShare_id()+" Total: "+this.getCount());
		
		mIvShareuserimage = ViewHolder.get(convertView, R.id.frag_share_first_iv_userImage);
		mTvUsername = ViewHolder.get(convertView, R.id.frag_share_first_tv_userName);
		mTvUsersource = ViewHolder.get(convertView, R.id.frag_share_first_tv_userSource);
		mTvTime = ViewHolder.get(convertView, R.id.frag_share_first_tv_time);
		mTvContent = ViewHolder.get(convertView, R.id.frag_share_first_tv_content);
		
		// 加载用户头像
		SDViewBinder.setImageView(mIvShareuserimage, model.getUseravatar());
		// 用户名
		mTvUsername.setText(model.getNick_name());

		// 来源和时间
		//mTvUsersource.setText(model.getSource());
		mTvUsersource.setVisibility(TextView.GONE);
		
		mTvTime.setText(model.getCreate_time());
		// 标题名称(含表情替换)
		if(model.getParse_expres()!=null)
		{
		if (model.getParse_expres().size() != 0)
		{
			String b = model.getContent();
			for (int i1 = 0; i1 < model.getParse_expres().size(); i1++)
			{
				String c = "\\[\\w*" + model.getParse_expres().get(i1).getKey() + "\\]";// expresList.get(i).getKey().toString();
				// \[[衰]\]
				String g = "<img src='" + model.getParse_expres().get(i1).getValue() + "'/>";
				String d = b.replaceAll(c, g);
				b = d;

				Spanned text2 = Html.fromHtml(b, new SDMyImageGetterUtil(nowActivity, mTvContent), null);
				mTvContent.setText(text2);
			}
		} else if (model.getParse_expres().size() == 0)
		{
			String textText = model.getContent();
			mTvContent.setText(textText);
		}
		}
		else
		{
			String textText = model.getContent();
			mTvContent.setText(textText);
			
		}
		
		
		LinearLayout mLlLinearAll = ViewHolder.get(convertView, R.id.frag_share_detail_second_ll_LinearAll);
		//List<ShareItemImageModel> mListShareItemImageModel = new ArrayList<ShareItemImageModel>();
		//List<ShareItemCollectModel> mListShareItemCollectModel = new ArrayList<ShareItemCollectModel>();
		LinearLayout commentListAll = null;
		final ArrayList<String> mListImageUrl = new ArrayList<String>();
		LinearLayout llImagesLine = null;
		
		//mListShareItemCollectModel = model.getCollects();
		//mListShareItemImageModel = model.getImgs();
//		if (mListShareItemImageModel != null && mListShareItemImageModel.size() > 0)
//		{
//			for (ShareItemImageModel imageModel : mListShareItemImageModel)
//			{
//				String url = imageModel.getImg();
//				mListImageUrl.add(url);
//			}
//		}
		String url = model.getImg();
		System.out.println("IMAGE: "+model.getImg());
		System.out.println("ORG_IMAGE:" + model.org_img);
		mListImageUrl.add(model.org_img);
		int cols = 1;
//		int picN = mListShareItemImageModel.size();
//		if (picN == 1){
//			cols = 1;
//		}else if (picN%2==0&&picN%3!=0){
//			cols = 2;
//		}else
//			cols = 3;
		
		mLlLinearAll.removeAllViews();
		//for (int i = 0; i < mListShareItemImageModel.size(); i++)
		int i = 0;
		{
			if (i % cols == 0)
			{
				llImagesLine = new LinearLayout(App.getApplication());
				llImagesLine.setOrientation(LinearLayout.HORIZONTAL);
				LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
				llImagesLine.setLayoutParams(lp);
				//llImagesLine.setPadding(60, 0, 0, 0);
				mLlLinearAll.addView(llImagesLine);
			}
			
			ImageView ivImage = new ImageView(App.getApplication());
			ivImage.setTag(i);
			ivImage.setOnClickListener(new OnClickListener()
			{
				
				@Override
				public void onClick(View v)
				{
					Intent intent = new Intent();
					intent.setClass(App.getApplication(), AlbumActivity.class);
					intent.putStringArrayListExtra(AlbumActivity.EXTRA_LIST_IMAGES, mListImageUrl);
					Object tag = v.getTag();
					if (tag != null)
					{
						try
						{
							int index = (Integer) tag;
							intent.putExtra(AlbumActivity.EXTRA_IMAGES_INDEX, index);
						} catch (Exception e)
						{
						}
					}
					nowActivity.startActivity(intent);
				}
			});
			//SDViewBinder.setImageView(ivImage, mListShareItemImageModel.get(i).getImg());
			
			class MyIL implements ImageLoadingListener{
				
				public LinearLayout mImagePart;
				public LinearLayout mCurLine;
				public ImageView mView;
				public int mCols;
				
				@Override
				public void onLoadingStarted(String imageUri, View view){
					System.out.println("!!BeginLoad!!");
				}
				
				@Override
				public void onLoadingFailed(String imageUri, View view, FailReason failReason){
					System.out.println("!!LoadFailed!!");
					mCurLine.removeView(mView);
					if (mCurLine.getChildCount()==0){
						mImagePart.removeView(mCurLine);
					}
				}
				
				@Override
				public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage){
					System.out.println("!!LoadFinished!!");
					
					int picW = 100, picH = 100;
					
					if (loadedImage == null){
						mCurLine.removeView(mView);
						if (mCurLine.getChildCount()==0){
							mImagePart.removeView(mCurLine);
						}
						return;
					}
					
					/*
					if (mCols == 1)
						picH = (int)(((float)picW/loadedImage.getWidth())*loadedImage.getHeight());
					if (picH >= picW*4)
						picH = picW*4;
					else if (picH <= 0)
						picH = 100;
					*/
					
					System.out.println("Image "+loadedImage.getWidth()+"X"+loadedImage.getHeight()+" "+picW+"X"+picH);
					
					//mView.setLayoutParams(new LinearLayout.LayoutParams(picW, picH));
					mView.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, picH));
					//mView.setScaleType(ScaleType.CENTER_CROP);
					mView.setScaleType(ScaleType.FIT_CENTER);
					mView.setPadding(0, 0, 5, 5);
					mView.setVisibility(ImageView.VISIBLE);
				}
				
				@Override
				public void onLoadingCancelled(String imageUri, View view){
					System.out.println("!!LoadCancel!!");
				}
			}
			
			llImagesLine.addView(ivImage);
			ivImage.setVisibility(ImageView.GONE);
			try
			{
				MyIL listener = new MyIL();
				
				listener.mCols = cols;
				listener.mImagePart = mLlLinearAll;
				listener.mCurLine = llImagesLine;
				listener.mView = ivImage;
				
				ImageLoader.getInstance().displayImage(model.getImg(), ivImage, ImageLoader.getInstance().getConfiguration().getDisplayImageOptions(), listener, null);
			} catch (Exception e)
			{
				System.out.println("NotFound!!!!!!");
				e.printStackTrace();
				//continue;
			}
		}
		
		//添加评论信息
		//refreshComment(convertView, model);
		//添加评论功能
		/**
		 * 自定义对话框的类
		 */
		/*
		class MyDialog extends Dialog
		{

			public MyDialog(Context context, int theme)
			{
				super(context, theme);
			}

			@Override
			protected void onCreate(Bundle savedInstanceState)
			{
				super.onCreate(savedInstanceState);
				this.setContentView(R.layout.dialog);

				// 退出按钮和返回按钮
				Button submit_button, return_button;
				final EditText content_text;

				// 初始化
				submit_button = (Button) findViewById(R.id.submit_button);
				return_button = (Button) findViewById(R.id.return_button);
				content_text = (EditText) findViewById(R.id.dlg_input_content);

				// 发表
				submit_button.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						if (content_text.getText().toString() == null || "".equals(content_text.getText().toString()))
						{
							Toast.makeText(nowActivity, "点评内容为空,发布失败!", Toast.LENGTH_LONG).show();
						} else
						{
							requestAddComment(mView, model.getShare_id(), content_text.getText().toString());
							dismiss();
						}
					}
				});

				// 返回
				return_button.setOnClickListener(new View.OnClickListener()
				{
					@Override
					public void onClick(View v)
					{
						// 关闭对话框
						dismiss();
					}
				});
			}

		}
		*/
		ImageView btnComment = ViewHolder.get(convertView, R.id.imageView1);
		btnComment.setVisibility(ImageView.GONE);
		
		/*
		btnComment.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!AppHelper.isLogin()) // 未登录
				{
					nowActivity.startActivity(new Intent(App.getApplication(), LoginNewActivity.class));
				} else
				{
					Dialog d = new MyDialog(nowActivity, R.style.MyDialog);
					d.show();

				}
			}
			
		});
		*/
		TextView tvCommentNums = ViewHolder.get(convertView, R.id.frag_share_comment_nums);
		//tvCommentNums.setText("评论: "+model.getComments().getList().size());
		tvCommentNums.setText("评论: "+model.getReply_count());
		
		//添加分割线
		LinearLayout llSep = ViewHolder.get(convertView, R.id.frag_share_sepline);
		if (position != this.getCount()-1){
			llSep.setVisibility(LinearLayout.VISIBLE);
		}else
			llSep.setVisibility(LinearLayout.GONE);
			
		//点击整个内容
		convertView.setOnClickListener(new OnClickListener(){
			
			@Override
			public void onClick(View v)
			{
				ArrayList<String> share2_list = new ArrayList<String>();
				for (int i = 0; i < mListModel.size(); i++)
				{
					share2_list.add(String.valueOf(mListModel.get(i).getShare_id()));
				}
				Intent intent = new Intent();
				intent.putExtra(ShareDetailActivity.EXTRA_SHARE_ID, model.getShare_id());
				intent.putExtra(ShareDetailActivity.EXTRA_PAGE_ID, mListModel.indexOf(model));
				intent.putStringArrayListExtra(ShareDetailActivity.EXTRA_SHARE_LIST, share2_list);
				intent.setClass(nowActivity, ShareDetailActivity.class);
				nowActivity.startActivity(intent);
			}
			
		});
		
		
		//点击用户头像
		mIvShareuserimage.setOnClickListener(new OnClickListener(){
		
			@Override
			public void onClick(View v)
			{
//				if (model != null && !AppHelper.isEmptyString(model.getShare_id()))
//				{
//					Intent intent = new Intent();
//					intent.setClass(nowActivity, UserCenterActivity.class);
//					intent.putExtra(UserCenterActivity.EXTRA_UID_ID, model.getShare_id());
//					nowActivity.startActivity(intent);
//				}
				ArrayList<String> share2_list = new ArrayList<String>();
				for (int i = 0; i < mListModel.size(); i++)
				{
					share2_list.add(String.valueOf(mListModel.get(i).getShare_id()));
				}
				Intent intent = new Intent();
				intent.putExtra(ShareDetailActivity.EXTRA_SHARE_ID, model.getShare_id());
				intent.putExtra(ShareDetailActivity.EXTRA_PAGE_ID, mListModel.indexOf(model));
				intent.putStringArrayListExtra(ShareDetailActivity.EXTRA_SHARE_LIST, share2_list);
				intent.setClass(nowActivity, ShareDetailActivity.class);
				nowActivity.startActivity(intent);
			}
			
		});
		
		
		return convertView;
	}
	
	protected void refreshComment(View convertView, ShareItemModel model){
		LinearLayout llCommentAll = ViewHolder.get(convertView, R.id.frag_share_comment_all);
		ShareItemCommentModel sicm = model.getComments();
		if (sicm.getList().size() > 0){
			//llCommentAll.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
			//llCommentAll.setPadding(70, 0, 0, 0);
			//llCommentAll.setBackgroundColor(Color.WHITE);
			llCommentAll.removeAllViews();
			//加入所有评论
			for (ShareItemCommentListModel m : sicm.getList()){
				addComment(llCommentAll, m);
			}
			llCommentAll.setVisibility(LinearLayout.VISIBLE);
		}else{
			llCommentAll.setVisibility(LinearLayout.GONE);
		}
	}

	protected void addComment(LinearLayout llCommentAll, ShareItemCommentListModel m){
		LinearLayout commentLine = new LinearLayout(App.getApplication());
		commentLine.setOrientation(LinearLayout.HORIZONTAL);
		commentLine.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
		//commentLine.setPadding(70, 2, 5, 2);
		llCommentAll.addView(commentLine);
		
		TextView act = new TextView(App.getApplication());
		act.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		act.setPadding(3, 1, 0, 0);
		act.setText(m.getUser_name()+":");
		act.setTextColor(Color.RED);
		act.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
		//act.setBackgroundColor(Color.WHITE);
		final String c_uid = m.getUid();
		act.setOnClickListener(new OnClickListener(){
		
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!AppHelper.isEmptyString(c_uid))
				{
					Intent intent = new Intent();
					intent.setClass(nowActivity, UserCenterActivity.class);
					intent.putExtra(UserCenterActivity.EXTRA_UID_ID, c_uid);
					nowActivity.startActivity(intent);
				}
			}
			
		});
		commentLine.addView(act);
		
		TextView content = new TextView(App.getApplication());
		content.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
		content.setPadding(3, 1, 2, 0);
		content.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 15);
		//content.setBackgroundColor(Color.WHITE);
		content.setTextColor(Color.BLACK);
		commentLine.addView(content);
		
		// 设置评论内容(表情替换)
		if (m.getParse_expres().size() != 0)
		{
			String b = m.getContent();
			for (int i1 = 0; i1 < m.getParse_expres().size(); i1++)
			{
				String c = "\\[\\w*" + m.getParse_expres().get(i1).getKey() + "\\]";// expresList.get(i).getKey().toString();
				// \[[衰]\]
				String g = "<img src='" + m.getParse_expres().get(i1).getValue() + "'/>";
				String d = b.replaceAll(c, g);
				b = d;

				Spanned text2 = Html.fromHtml(b, new SDMyImageGetterUtil(nowActivity, content), null);
				content.setText(text2);
				
				System.out.println("Content: "+text2.toString());
			}
		} else if (m.getParse_expres().size() == 0)
		{
			String text1 = m.getContent();
			content.setText(text1);
			System.out.println("Content: "+text1);
		}
	}
	
	/**
	 * 发表评论接口
	 */
	protected void requestAddComment(final View v, final String share_id, String content)
	{
		RequestModel model = new RequestModel();
		model.put("act", "addcomment");
		LocalUserModel user = App.getApplication().getmLocalUser();
		if (user != null)
		{
			model.put("email", user.getUser_name());
			model.put("pwd", user.getUser_pwd());
		}
		model.put("share_id", share_id);
		model.put("source", "来自android客户端");
		model.put("is_relay", 1);
		model.put("parent_id", 0);
		model.put("content", content);
		RequestCallBack<String> handler = new RequestCallBack<String>()
		{

			@Override
			public void onStart()
			{

			}

			@Override
			public void onSuccess(ResponseInfo<String> responseInfo)
			{
				BaseActModel actModel = JsonUtil.json2Object(responseInfo.result, BaseActModel.class);
				if (!SDInterfaceUtil.isActModelNull(actModel))
				{
					if (actModel.getResponse_code() == 1)
					{
						int status = SDTypeParseUtil.getIntFromString(actModel.getStatus(), 0);
						if (status == 1)
						{
							requestAndRefreshComment(v, share_id);
						} else if (status == 0)
						{
							SDToast.showToast("发表评论失败");
						}
					}
				}
			}

			@Override
			public void onFailure(HttpException error, String msg)
			{

			}

			@Override
			public void onFinish()
			{

			}
		};

		InterfaceServer.getInstance().requestInterface(model, handler);

	}
	
	private void requestAndRefreshComment(final View v, final String share_id)
	{
		if (share_id != null)
		{
			RequestModel model = new RequestModel();
			model.put("act", "share");
			if (AppHelper.isLogin())
			{
				model.put("email", AppHelper.getLocalUser().getUser_name());
				model.put("pwd", AppHelper.getLocalUser().getUser_pwd());
			}
			model.put("share_id", share_id);
			RequestCallBack<String> handler = new RequestCallBack<String>()
			{

				@Override
				public void onStart()
				{
					//AppHelper.showLoadingDialog("请稍候...");
				}

				@Override
				public void onSuccess(ResponseInfo<String> responseInfo)
				{
					ShareActModel actModel = JsonUtil.json2Object(responseInfo.result, ShareActModel.class);
					if (!SDInterfaceUtil.isActModelNull(actModel))
					{
						if (actModel.getResponse_code() == 1)
						{
							refreshComment(v, actModel.getItem());
						}
					}
				}

				@Override
				public void onFailure(HttpException error, String msg)
				{

				}

				@Override
				public void onFinish()
				{
					//AppHelper.hideLoadingDialog();
				}
			};

			InterfaceServer.getInstance().requestInterface(model, handler);
		}

	}
}
